import {useEditor,Element, useNode} from '@craftjs/core';
import React from 'react';
import {ChatModal} from '../chat-modal';
import {useLoadComponents} from "../../utils/loadComponents";

type StageProps = {
    children?: React.ReactNode;
};

// const createNode = (actions: any, query: any, values: any) => {
//     const fieldsConfig = values
//         .actions
//         .find((action: any) => action.type === 'Form')
//         .fields.map((field: any) => {
//             const {eventReferrence: {fieldKey, fieldType, label, rules = [], defaultValue, options = []}} = field

//             return {
//                 field: fieldKey,
//                 valueType: fieldType,
//                 label,
//                 rules,
//                 defaultValue: Array.isArray(defaultValue) ? defaultValue.map(ret => new Date(ret * 1000)) : defaultValue,
//                 options
//             }
//         })

//     const proFormNode = <Form
//         labelCol={{span: 3}}
//         fieldsConfig={fieldsConfig}
//     />

//     const nodeTree = query
//         .parseReactElement(proFormNode)
//         .toNodeTree();

//     actions.addNodeTree(nodeTree, 'ROOT');
// };

export const Stage: React.FC<StageProps> = ({children}) => {
    const editData = useEditor();
    const {actions, query} = editData;
    const {connectors:{connect,drag}} = useNode()

    const clearCanvas = () => {
        // 获取 ROOT 节点下的所有子节点，并逐一删除
        const nodeMaps = query.getNodes();
        if (nodeMaps) {
            Object.values(nodeMaps).forEach(node => {
                if (node.id === 'ROOT') return;
                actions.delete(node.id);
            });
        }
    };

    return (
        <>
            <div ref={dom => connect(drag(dom as HTMLElement))} style={{
                padding: 20,
                minHeight: 520,
                border: '1px solid #9d9d9d'
            }}>
                {children}
            </div>
        </>
        
    );
};
